package gov.fema.hazus.bdc.client.login;

import gov.fema.hazus.bdc.client.common.entities.AbstractClickListener;
import gov.fema.hazus.bdc.client.common.handlers.LoggingAsyncHandler;
import gov.fema.hazus.bdc.client.common.ui.Message;
import gov.fema.hazus.bdc.client.controller.Controller;
import gov.fema.hazus.bdc.shared.entity.User;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ButtonBase;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class Login extends Composite {

     
    private class LoginClickListener extends AbstractClickListener
    {
        @Override
        public void handleClick(Widget sender) {
            
            user.setUsername(userNameTextBox.getText());
            user.setPassword(passordTextBox.getText());
            login();
            
        }   
    }
    
    public class LoginPasswordTextBoxKeyListener extends KeyboardListenerAdapter
    {
        public void onKeyDown(Widget sender, char keyCode, int modifiers)
        {
            clearLoginFailure();
        	if( (int) keyCode == KEY_ENTER)
            {
                user.setUsername(userNameTextBox.getText());
                user.setPassword(passordTextBox.getText());
                login();
            }
        }
    }    
    
    private class LoginHandler extends LoggingAsyncHandler
    {

        @Override
        public void handleFailure(Throwable caught) {
            GWT.log("LoginUpdater: Send message to UI:" + caught, null);
            displayLoginFailure(caught.getMessage());
        }

        @Override
        public void handleSuccess(Object result) {
            setLoginCookie("true");
            setUserCookie();
            user = (User) result;
            Controller.get().mainLogin();
        }
    }
    
    /**
     * Set up instance for Login
     */
	private static Login singleton;
	public static Login get()
	{
		if( singleton == null )
        {
		    singleton = new Login();
        }
        return singleton;
	}

	private Message message;
    


	// public members
    VerticalPanel panel = new VerticalPanel();
    FlexTable table = new FlexTable();
    
    Button loginButton = new Button();
    TextBox userNameTextBox = new TextBox();
    PasswordTextBox passordTextBox = new PasswordTextBox();

    private User user = new User();
    
    private HorizontalPanel main;
    private LoginConstants loginConstants;
    private static final String COOKIE_NAME_LOGIN = "___InCastLogin___";
    private static final Date DATE_IN_THE_FUTURE = new Date(61854274800000L);
    private static final String COOKIE_NAME_USER = "___InCastUserName___"; 

    public Login()
    {
        
    	singleton = this;
    	
        loginConstants = (LoginConstants)GWT.create(LoginConstants.class);
        loginButton.setText( loginConstants.loginButton() );
        
        user = new User();
        
        userNameTextBox.addKeyboardListener(new LoginPasswordTextBoxKeyListener() );
        passordTextBox.addKeyboardListener(new LoginPasswordTextBoxKeyListener() );
        loginButton.addClickListener(new LoginClickListener());
        
        table.setWidget(0, 1, userNameTextBox);
        table.setWidget(1, 1, passordTextBox);
        table.setWidget(2, 1, loginButton);
        
        panel.add(table);

        main = new HorizontalPanel();
        
        Image logo = new Image("images/incast/hazus.logo.long.jpg");
        logo.setHeight("54");
        logo.setWidth("400");
        logo.setStyleName("logo");
        
        table.setWidget(0, 0, logo);
        table.getFlexCellFormatter().setColSpan(0, 0, 2);

        Label userNameLabel = new Label(loginConstants.loginUserName());
        Label passwordLabel = new Label(loginConstants.loginPassword());

        table.setWidget(1, 0, userNameLabel);
        table.setWidget(1, 1, userNameTextBox);
        
        table.setWidget(2, 0, passwordLabel);
        table.setWidget(2, 1, passordTextBox);
        
        table.setWidget(3, 1, loginButton);
        
        table.getFlexCellFormatter().setColSpan(4, 0, 2);
        table.getFlexCellFormatter().setAlignment(4, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_MIDDLE);
        
        message = new Message();
        table.setWidget(4, 0, message);
        
        userNameTextBox.setText("");
        passordTextBox.setText("");

        main.add(table);

        main.setStylePrimaryName("login-panel");
        main.setCellHorizontalAlignment(table, HasHorizontalAlignment.ALIGN_CENTER);

        initWidget(main);
    }
    
    public User getLoginUser()
    {
        return user;
    }
    
    public void displayLoginFailure(String text) {
    	message.setText(text);
	}
    
    public void clearLoginFailure()
    {
    	message.setText("");
    }
    
    public boolean isValid() {
        
        String loggedIn = Cookies.getCookie(COOKIE_NAME_LOGIN);
        if( loggedIn == null )
        {
            return false;
        }
        if( loggedIn.equalsIgnoreCase("true")){
            return true;
        }
        else
        {
            return false;
        }

    }   
    
    public void login()
    {
        GWT.log("loginUser=" + user.toString(), null);
        LoginServiceProxy.get().login(user, new LoginHandler());
    }
    
    public void logout()
    {
        user = new User();
        Cookies.removeCookie(COOKIE_NAME_LOGIN);
        Cookies.removeCookie(COOKIE_NAME_USER);
        Controller.get().mainLogout();
    }    
    
    public void setUserCookie() {
        Cookies.setCookie(COOKIE_NAME_USER, this.user.getUsername(), DATE_IN_THE_FUTURE);
    }
    
    public void setLoginCookie(String loggedIn)
    {
        Cookies.setCookie(COOKIE_NAME_LOGIN, loggedIn, DATE_IN_THE_FUTURE);
    } 

    public String getUserNameFromCookie() {
        return Cookies.getCookie(COOKIE_NAME_USER);
    }    
    
    public void setFocus()
    {
        userNameTextBox.setFocus(true);
    }

	public void show() {
		this.show();
	}

    
}
